package com.yjr.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.yjr.common.constant.ProductConstant;
import com.yjr.common.to.SkuReductionTO;
import com.yjr.common.to.SpuBoundTO;
import com.yjr.common.to.es.SkuEsModel;
import com.yjr.common.to.es.SkuHasStockVo;
import com.yjr.common.utils.R;
import com.yjr.gulimall.product.entity.*;
import com.yjr.gulimall.product.feign.CouponFeignService;
import com.yjr.gulimall.product.feign.SearchFeignService;
import com.yjr.gulimall.product.feign.WareFeignService;
import com.yjr.gulimall.product.service.*;
import com.yjr.gulimall.product.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjr.common.utils.PageUtils;
import com.yjr.common.utils.Query;

import com.yjr.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo vo) {
        //先保存spu的基本信息  pms_spu_info
        SpuInfoEntity spuInfoEntity=new SpuInfoEntity();
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(vo, spuInfoEntity);
        this.saveBatchSpuInfo(spuInfoEntity);
        //保存spu的描述图片  pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);
        //保存spu的图片集  pms_spu_images
        // 先获取所有图片
        List<String> images = vo.getImages();
        // 保存图片的时候 并且保存这个是那个spu的图片
        spuImagesService.saveImages(spuInfoEntity.getId() ,images);
        //保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(attr.getAttrId());
            // 可能页面没用传入属性名字 根据属性id查到所有属性 给名字赋值
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(attrEntity.getAttrName());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setSpuId(spuInfoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);
        //保存spu的积分信息  sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTO spuBoundTO = new SpuBoundTO();
        BeanUtils.copyProperties(bounds, spuBoundTO);
        spuBoundTO.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTO);
        if(r.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }
        //保存spu对应的所有sku信息
        List<Skus> skus = vo.getSkus();
        if(skus != null && skus.size() > 0){
            // 提前查找默认图片
            skus.forEach(item -> {
                String dufaultImg = "";
                for (Images img : item.getImages()) {
                    if(img.getDefaultImg() == 1){
                        dufaultImg = img.getImgUrl();
                    }
                }
                // 2).基本信息的保存 pms_sku_info
                // skuName 、price、skuTitle、skuSubtitle 这些属性需要手动保存
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                // 设置spu的品牌id
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(dufaultImg);
                skuInfoEntity.setSaleCount((long) (Math.random()*2888));
                skuInfoService.saveSkuInfo(skuInfoEntity);

                // 3).保存sku的图片信息  pms_sku_images
                // sku保存完毕 自增主键就出来了 收集所有图片
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity ->
                        // 返回true就会保存 返回false就会过滤
                        !StringUtils.isEmpty(entity.getImgUrl())
                ).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);

                // 4).sku的销售属性  pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    // 对拷页面传过来的三个属性
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 5.) sku的优惠、满减、会员价格等信息  [跨库]
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                BeanUtils.copyProperties(item, skuReductionTO);
                skuReductionTO.setSkuId(skuId);
                if(skuReductionTO.getFullCount() > 0 || (skuReductionTO.getFullPrice().compareTo(new BigDecimal("0")) > 0)){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTO);
                    if(r1.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }

    }

    @Override
    public void saveBatchSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            spuInfoEntityQueryWrapper.and(queryWrapper -> queryWrapper.eq("id",key).or().like("spu_name",key));
        }
        String status = (String) params.get("status");
        if(StringUtils.isNotEmpty(status)){
            spuInfoEntityQueryWrapper.eq("publish_status",status);
        }
        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            spuInfoEntityQueryWrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if(StringUtils.isNotEmpty(catelogId)&& !"0".equalsIgnoreCase(catelogId)){
            spuInfoEntityQueryWrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                spuInfoEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {

        //根据spuId查询对应的sku集合
        List<SkuInfoEntity> skuInfoEntities=skuInfoService.listBySpuId(spuId);
        if(!CollectionUtils.isEmpty(skuInfoEntities)){
            List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

            //封装属性集合
            //根据spuId查询当前spu的属性
            List<ProductAttrValueEntity> productAttrValueEntities=attrValueService.baseAttrListForSpu(spuId);
            if(!CollectionUtils.isEmpty(productAttrValueEntities)){
                List<Long> attrIds = productAttrValueEntities.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
                List<Long> searchAttrId=attrService.listSearchAttrs(attrIds);
                HashSet<Long> searchAttrIdSet = new HashSet<>(searchAttrId);
                List<SkuEsModel.Attrs> attrsList = productAttrValueEntities.stream().filter(productAttrValueEntity -> searchAttrIdSet.contains(productAttrValueEntity.getAttrId())).map(
                        productAttrValueEntity -> {
                            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                            BeanUtils.copyProperties(productAttrValueEntity, attrs);
                            return attrs;
                        }
                ).collect(Collectors.toList());

                //调用远程仓库判断sku是否有库存
                Map<Long,Boolean> stockMap=null;

                try {
                    R skuHasStock = wareFeignService.getSkuHasStock(skuIds);
                    stockMap=skuHasStock.getData(new TypeReference<List<SkuHasStockVo>>(){}).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId,item->item.getHasStock()));
                    log.warn("服务调用成功" + skuHasStock);
                } catch (Exception e) {
                    log.error("库存服务调用失败: 原因{}",e);
                    e.printStackTrace();
                }
                Map<Long,Boolean> finalStockMap=stockMap;

                List<SkuEsModel> collect = skuInfoEntities.stream().map(skuInfoEntity -> {
                    SkuEsModel esModel = new SkuEsModel();
                    BeanUtils.copyProperties(skuInfoEntity, esModel);
                    esModel.setSkuPrice(skuInfoEntity.getPrice());
                    esModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
                    if (finalStockMap == null) {
                        esModel.setHasStock(true);
                    } else {
                        esModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
                    }
                    // TODO 1.热度评分 0
                    esModel.setHotScore(0L);

                    BrandEntity brandEntity = brandService.getById(esModel.getBrandId());

                    // brandName、brandImg
                    esModel.setBrandName(brandEntity.getName());
                    esModel.setBrandImg(brandEntity.getLogo());

                    // 查询分类信息
                    CategoryEntity categoryEntity = categoryService.getById(esModel.getCatalogId());
                    esModel.setCatalogName(categoryEntity.getName());

                    // 保存商品的属性
                    esModel.setAttrs(attrsList);
                    return esModel;
                }).collect(Collectors.toList());



                //远程调用
                R r = searchFeignService.productStatusUp(collect);
                if(r.getCode()==0){
             		// 远程调用成功
                    baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
                }
                else {
                    // 远程调用失败 TODO 接口幂等性 重试机制
                    /**
                     * Feign 的调用流程  Feign有自动重试机制
                     * 1. 发送请求执行
                     * 2.
                     */
                }

            }

        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        return getById(skuInfoService.getById(skuId).getSpuId());
    }

}